﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PermissionAuthenticationDemo.Common;
using PermissionAuthenticationDemo.Service;
using PermissionAuthenticationDemo.Utility.Service;
using PermissionAuthenticationDemo.Config;
using System.Security.Claims;
using OaEntity.Models;
using OaEntity.DTO;
using OaEntity.CustomModel;

namespace PermissionAuthenticationDemo.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private IJWTService _IJWTService;

        private IUserService userService;

        #region Identity
        private readonly ILogger<UserController> _logger;

        private readonly OaContext oaContext;

        private IConfiguration _iConfiguration;

        public UserController(ILogger<UserController> logger, IConfiguration configuration, IJWTService jWTService, OaContext oaContext, IUserService userService)
        {
            _logger = logger; //输入日志书写   _logger.LogInformation("");
            this._iConfiguration = configuration;
            this._IJWTService = jWTService;
            this.oaContext = oaContext;
            this.userService = userService;
        }
        #endregion

        /// <summary>
        /// 登录成功，返回token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<LoginResult<Tcauser>> GetTokenLogin([FromBody] UserLogin user)
        {
            return userService.GetToken(user.userName, user.password);
        }

        /// <summary>
        /// 获取当前用户的ID
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize] //需要通过验证之后，从Claim中获取对应的数据
        public async Task<int> GetCurrentUserIdAsync()
        {
            return Convert.ToInt32(User.FindFirstValue(ClaimTypes.Sid));
        }

        /// <summary>
        /// 登录接口，若登录成功则请求获取token
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult login(string username, string password)
        {
            if ("admin".Equals(username) && "123".Equals(password))
            {
                //生成token
                var token = this._IJWTService.GetToken(username);

                return new JsonResult(new
                {
                    Result = true,
                    Token = token
                });
            }
            else
            {
                return new JsonResult(new
                {
                    Result = false,
                    Token = ""
                });
            }
        }


        /// <summary>
        /// 根据id获取User数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[HttpGet]
        //[Authorize]     //要求通过授权才行
        //public User GetUserById(int id)
        //{
        //    //var u = this._iUserService.FindUser(id);
        //    return new User()
        //    {
        //        Id = id,
        //        Account = "admin" + "MA",
        //        Name = "Admin",
        //        Role = "Administrator",
        //        Email = "2043708045@qq.com",
        //        LoginTime = DateTime.Now,
        //        Password = "admin" + "K8S"
        //    };
        //}

        /// <summary>
        /// 根据ID查找用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<ApiResult<Tcauser>> GetUserById(int userID)
        {
            var users = oaContext.Tcausers.Where(x => x.UserId == userID).FirstOrDefault();

            var total = 1;

            if (users != null)
            {
                return ApiResult<Tcauser>.Success(users, total);
            }
            else
            {
                return ApiResult<Tcauser>.Error(users, total);
            }
        }

        [HttpPost]
        [Authorize]
        public async Task<ICollection<Tcauser>> GetUsersAll()
        {
            return oaContext.Tcausers.ToList();
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task AddUser([FromBody] User user)
        {
            //开启事物
            var transaction = oaContext.Database.BeginTransaction();
            try
            {
                ToMD5<string> toMd5 = new ToMD5<string>();
                var currentUserId = await GetCurrentUserIdAsync();
                var saveUserEntity = new Tcauser
                {
                    UserId = 0,
                    UserName = user.userName,
                    Password = toMd5.GetMD5Dat(user.Password),
                    Phone = user.phone,
                    Email = user.Email,
                    Status = 1,
                    IsDelete = false,
                    OperateTime = DateTime.Now,
                    Operater = Convert.ToInt32(currentUserId),
                };
                await oaContext.AddAsync(saveUserEntity);
                await oaContext.SaveChangesAsync();
                //提交事物
                await transaction.CommitAsync();
            }
            catch(Exception e)
            {
                await transaction.RollbackAsync();
            }
            
        }
    }
}
